import { createStore } from "solid-js/store";
import * as apis from "@/apis/auth";

type Auth = ({ status: "ok" } & Me) | ({ status: "failed" | "loading" } & Partial<Me>);

const [auth, setAuth] = createStore<Auth>({ status: "loading" });

export default function useAuthStore() {
  const load = async () => {
    try {
      setAuth({ status: "loading" });
      const me = await apis.profile();
      setAuth({ status: "ok", ...me });
    } catch (err) {
      console.log("get profile failed", err);
      setAuth({ status: "failed" });
    }
  };

  const login = async (username: string, password: string): Promise<{ ok: true } | { ok: false; message: string }> => {
    try {
      setAuth({ status: "loading" });
      const me = await apis.login({ username, password });
      setAuth({ status: "ok", ...me });
      return { ok: true };
    } catch (err) {
      setAuth({ status: "failed" });
      return { ok: false, message: (err as Error).message };
    }
  };

  const logout = async () => {
    await apis.logout();
    setAuth({ status: "failed" });
  };

  return { auth, load, login, logout };
}
